
<template>
	<div class="xiazaierweima"></div>
</template>

<script>
  import QRCode from 'qrcodejs2'
  import * as qiniu from 'qiniu-js'
	export default {
		name: 'xiazaierweima',
    props:['item'],
		data() {
			return {
        all:""
			}
		},
		created() {
      console.log('item1111',this.item)
		},
		mounted() {

		},
		methods: {
      getinfo:function(){

        let url = `/own/mstore/info`
        axios.get(url).then((response)=>{
        	if (response.data.msg.code == 0) {
            this.all = response.data.data
            this.haibao(this.item)
        	} else {
        		this.$message.error(response.data.msg.info);
        	}
        })
      },
      //生成个商品海报
      haibao:function(item){

        if(!item.share_img){
          item.share_img = item.image1
        }

        var that = this
        var img2x = ''
        var d = ""
        let p0 = new Promise((res,rej)=>{
          var url2 = `${location.origin}/h5/order?id=${item.id}`

          if(document.getElementById('erweimadiv')){
            document.getElementById('erweimadiv').innerHTML = ""
            d = document.getElementById('erweimadiv')
          }else{
            d = document.createElement('div')
            d.setAttribute('id','erweimadiv')
            document.body.appendChild(d)
          }

          var qrcode = new QRCode(document.getElementById('erweimadiv'), {
              text: url2,
              width: 220,
              height: 220,
              colorDark : "#000000",
              colorLight : "#ffffff",
              correctLevel : QRCode.CorrectLevel.H
          })
          var canvas = document.getElementById("erweimadiv").getElementsByTagName("canvas")[0];
          img2x = canvas.toDataURL("image/png");

          document.getElementById("erweimadiv").style.position = 'absolute'
          document.getElementById("erweimadiv").style.left = '-1000px'

          res('ok')
        })
        p0.then(()=>{
          var canvas = document.createElement('canvas')
          canvas.width = 750
          canvas.height = 300
          var ctx = canvas.getContext('2d');
          var canvas_h = 0
          var img = new Image();
          let p = new Promise((res,rej)=>{

          	if(item.share_img){
          		img.src = item.share_img
          		img.setAttribute("crossOrigin",'Anonymous')
          		img.onload = function() {
          			let img_w = 750
          			let bili = 750 / img.width
          			let img_h = parseInt(img.height * bili)
          			canvas_h = img_h
          			canvas.setAttribute("height", canvas_h + 260);
          			ctx.drawImage(img,0,0,img_w,img_h);  // 将图像绘制到Canvas上
          			res('ok')
          		};
          		img.onerror = function(err){
          			// that.msg = JSON.stringify(err)
          		}
          	}else{
              that.$message.error('没有分享图不能分享');
              return
          		// res('ok')
          	}
          })
          p.then(()=>{

          	var img2 = new Image();
          	img2.src = img2x

          	img2.setAttribute("crossOrigin",'Anonymous')
          	img2.onload = function() {

              ctx.fillStyle = '#000';
              ctx.font = "bold 28px microsoft yahei";
              ctx.maxWidth = '400px'
              ctx.textBaseline = "top";

              let hang1 = item.title.substring(0,18) || ''
              let hang2 = item.title.substring(18,36) || ''
              ctx.fillText(hang1, 30,canvas_h+35)
              ctx.fillText(hang2, 30,canvas_h+70)


              // ctx.fillText(item.title,30,canvas_h+30)

              ctx.drawImage(img2,520,canvas_h+30,200,200);


              ctx.fillStyle = '#000';
              ctx.font = "bold 24px microsoft yahei";
              ctx.lineHight = "40px";
              ctx.maxWidth = '300px'
              ctx.lineHeight = '40px'
              ctx.textBaseline = "top";
              ctx.fillText(that.all.store_name,85,canvas_h+120)


              ctx.fillStyle = 'rgb(175, 179, 188)';
              ctx.font = "normal 20px microsoft yahei";
              ctx.textBaseline = "top";
              ctx.fillText('长按识别二维码 进入下单链接',30,canvas_h+190)


              var img22 = new Image();
              img22.src = that.all.left_pic
              img22.setAttribute("crossOrigin",'Anonymous')

              img22.onload = function() {
                ctx.drawImage(img22,30,canvas_h+110,40,40);
                var radius = 50;
                // 开始绘制圆角矩形路径
                ctx.beginPath();
                // 左上角
                ctx.arc(radius, radius, radius, Math.PI, Math.PI * 1.5);
                // 右上角
                ctx.arc(canvas.width - radius, radius, radius, Math.PI * 1.5, Math.PI * 2);
                // 右下角
                ctx.arc(canvas.width - radius, canvas.height - radius, radius, 0, Math.PI * 0.5);
                // 左下角
                ctx.arc(radius, canvas.height - radius, radius, Math.PI * 0.5, Math.PI);
                // 结束绘制路径
                ctx.closePath();
                // 将路径限制到绘图区域内
                ctx.clip();
                ctx.drawImage(img22,30,canvas_h+110,40,40);

                var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
                for(var i = 0; i < imageData.data.length; i += 4) {
                	if(imageData.data[i + 3] == 0) {
                		imageData.data[i] = 255;
                		imageData.data[i + 1] = 255;
                		imageData.data[i + 2] = 255;
                		imageData.data[i + 3] = 255;
                	}
                }
                ctx.putImageData(imageData, 0, 0);
                var url = canvas.toDataURL('image/png');


                var ua = window.navigator.userAgent.toLowerCase();
                if (ua.match(/micromessenger/i) == 'micromessenger') {
                  //若是微信环境
                  const blob = that.base64ImgtoFile(url)
                  that.uploadok(blob)

                }else{
                  //若不是微信环境


                  // console.log(window.Android)
                  // var isAndroid = ua.indexOf('Android') > -1 || ua.indexOf('android') > -1 || ua.indexOf('Adr') > -1;
                  // if (isAndroid) {
                  //   window.Android.toast('开始下载图片，请等待...')

                  //   window.Android.setFileName('haibao.png')
                  //   window.Android.getBase64FromBlobData(url, 'image/png')
                  // }else{

                  // }

                  const blob = that.base64ImgtoFile(url)
                  that.uploadok(blob)
                  // var addElement = document.createElement('a')
                  // addElement.href = url
                  // addElement.download = "海报.png"
                  // document.body.appendChild(addElement)
                  // addElement.click();
                  // document.body.removeChild(addElement);
                  // document.body.removeChild(d)


                }
              }
          	}
          })
        })
        // this.xuanzhongde = item
        // let erweima = ""
        // if(this.$route.query.shops_id){
        //   erweima = `${location.origin}/h5/order?id=${this.xuanzhongde.id}&shops_id=${this.$route.query.shops_id}`
        // }else{
        //   if(this.$route.query.shop_id){
        //     erweima = `${location.origin}/h5/order?id=${this.xuanzhongde.id}&shop_id=${this.$route.query.shop_id}`
        //   }else{
        //     erweima = `${location.origin}/h5/order?id=${this.xuanzhongde.id}`
        //   }
        // }
        // let share_img = ''
        // if(this.xuanzhongde.share_img){
        //   share_img = this.xuanzhongde.share_img
        // }else{
        //   if(this.xuanzhongde.image1){
        //     share_img = this.xuanzhongde.image1
        //   }
        // }
        // this.$router.push({
        //   path:"/haibao",
        //   query:{
        //     share_img:share_img,
        //     logo:this.all.left_pic,
        //     erweima:erweima,
        //     title:this.xuanzhongde.title,
        //     shopname:this.all.store_name
        //   }
        // })



      },
      base64ImgtoFile(dataurl, filename = 'file') {
              //将base64格式分割：['data:image/png;base64','XXXX']
              const arr = dataurl.split(',')
              // .*？ 表示匹配任意字符到下一个符合条件的字符 刚好匹配到：
              // image/png
              const mime = arr[0].match(/:(.*?);/)[1]  //image/png
              //[image,png] 获取图片类型后缀
              const suffix = mime.split('/')[1] //png
              const bstr = atob(arr[1])   //atob() 方法用于解码使用 base-64 编码的字符串
              let n = bstr.length
              const u8arr = new Uint8Array(n)
              while (n--) {
                  u8arr[n] = bstr.charCodeAt(n)
              }
              return new File([u8arr], `${filename}.${suffix}`, {
                  type: mime
              })
      },
      uploadok: function(file) {
        let name = this.getRandomChar() + '.' + file.name.split('.')[1]
        var that = this
        axios.post(`/api/qiniu/uploadtoken`,{name:name})
          .then(response => {
            if(response.data.msg.code == 0){
              const observer = {
                next(res){
                  console.log(res)
                },
                error(err){
                  console.log(err)
                },
                complete(res){
                  that.$emit('guanbiloadlog')
                  var ua = window.navigator.userAgent.toLowerCase();
                  if (ua.match(/micromessenger/i) == 'micromessenger') {
                    location.href = 'https://gperson.gantanhaokeji.top/'+ res.key
                  }else{
                    location.href = 'https://gperson.gantanhaokeji.top/'+ res.key + '?attname='
                  }
                }
              }
              const observable = qiniu.upload(file,name, response.data.data.token, {}, {})
              const subscription = observable.subscribe(observer) // 上传开始
            }else{
              that.$emit('guanbiloadlog')
              this.$message.error(response.data.msg.info);
            }
          });
      },
      getRandomChar:function(len = 11)  {
        var  x = "0123456789qwertyuioplkjhgfdsazxcvbnm" // 需要什么字符这里添加
        var  tmp = ""
        var timestamp = new Date().getTime();
        for(var  i=0;i<len;i++)  {
          tmp += x.charAt(Math.ceil(Math.random()*100000000)%x.length);
        }
        return  timestamp+tmp;
      }



		}
	}
</script>


<style scoped lang="less">


</style>

